package com.example.study.jetpack.compose

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.content.res.Resources
import android.graphics.Typeface
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowInsets
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.compose.foundation.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.CornerSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.*
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
import androidx.compose.ui.graphics.drawscope.translate
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.layoutId
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.compose.ui.window.DialogProperties
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.ConstraintSet
import androidx.constraintlayout.compose.Dimension
import androidx.core.content.ContextCompat.startActivity
import androidx.core.view.WindowCompat
import androidx.core.view.doOnLayout
import androidx.lifecycle.LifecycleOwner
import androidx.navigation.NavHostController
 
import com.example.study.ui.theme.Teal200
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.lang.Math.cos
import java.lang.Math.sin
import java.util.*
import kotlin.math.roundToInt
import kotlin.random.Random

/**
 *  created by 20300
 *   on 2022/4/14
 *   describe:
 */
class Compose简例 {

    @Composable
    fun Row和Column(){
        Column() {
            Column(
                modifier = Modifier
                    .padding(bottom = 10.dp)
                    .background(Color.Green),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.SpaceEvenly
            ) {
                Text(text = "Hello")
                Text(text = "World")
                Text(text = "Fill")
            }
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .fillMaxHeight(0.5f)
                    .background(Color.Green),
                horizontalArrangement = Arrangement.SpaceEvenly,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(text = "Hello", modifier = Modifier.padding(end = 10.dp))
                Text(text = "World", modifier = Modifier.padding(end = 10.dp))
                Text(text = "Fill", modifier = Modifier.padding(end = 10.dp))
            }

            Row(
                modifier = Modifier
                    .padding(top = 20.dp)
                    .width(300.dp)
                    .height(200.dp)
                    .background(Color.Green),
                horizontalArrangement = Arrangement.SpaceEvenly,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(text = "Hello", modifier = Modifier.padding(end = 10.dp))
                Text(text = "World", modifier = Modifier.padding(end = 10.dp))
                Text(text = "Fill", modifier = Modifier.padding(end = 10.dp))
            }
        }
    }

    @Composable
    fun 属性modifier(){
        Column() {
            Column(
                modifier = Modifier
                    .padding(bottom = 10.dp)
                    .background(Color.Green),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.SpaceEvenly
            ) {
                Text(text = "Hello")
                Text(text = "World")
                Text(text = "Fill")
            }


            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .fillMaxHeight(0.5f)
                    .background(Color.Green),
                horizontalArrangement = Arrangement.SpaceEvenly,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(text = "Hello", modifier = Modifier.padding(end = 10.dp))
                Text(text = "World", modifier = Modifier.padding(end = 10.dp))
                Text(text = "Fill", modifier = Modifier.padding(end = 10.dp))
            }

            Row(
                modifier = Modifier
                    .padding(top = 20.dp)
                    .width(300.dp)
                    .height(200.dp)
                    .background(Color.Green),
                horizontalArrangement = Arrangement.SpaceEvenly,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(text = "Hello", modifier = Modifier.padding(end = 10.dp))
                Text(text = "World", modifier = Modifier.padding(end = 10.dp))
                Text(text = "Fill", modifier = Modifier.padding(end = 10.dp))
            }
        }
    }

    @Composable
    fun card图片(){
        val painter = painterResource(id =R.mipmap.yuanshi)
        val des = "this is android test"
        val title = "This is Title of image"
        Box(
            modifier = Modifier
                .fillMaxWidth(0.5f)
                .padding(16.dp)
        ) {
            ShowImageCard(title = title, des = des, painter = painter)
        }

    }
    @Composable
    fun ShowImageCard(title: String, des: String, painter: Painter, modifier: Modifier = Modifier) {
        Card(
            modifier = modifier.fillMaxWidth(),
            shape = RoundedCornerShape(15.dp),
            elevation = 5.dp
        ) {

            Box(modifier = Modifier.height(200.dp)) {
                Image(
                    painter = painter,
                    contentDescription = des,
                    contentScale = ContentScale.Crop
                )
                //拉渐变
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .background(
                            brush = Brush.verticalGradient(
                                colors = listOf(
                                    Color.Transparent,
                                    Color.Black
                                ),
                                startY = 300f//数据越大黑色越少
                            )
                        )
                )
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(16.dp),
                    contentAlignment = Alignment.BottomStart
                )
                {
                    Text(title, style = TextStyle(color = Color.White, fontSize = 16.sp))
                }
            }
        }
    }

    //字体详细:https://blog.csdn.net/u010436867/article/details/117390918

    @Composable
    fun 撰写状态(){
        Column(modifier = Modifier.fillMaxSize()) {
            //记住颜色状态不会重复赋值
            val color = remember {
                mutableStateOf(
                    Color.Gray
                )
            }
            ClickBox(
                modifier = Modifier
                    .weight(1f)
                    .fillMaxSize()
            ) {
                //产生的Color颜色回调到这里 给color赋值
                color.value = it
            }
            Box(
                modifier = Modifier
                    .background(color = color.value)
                    .weight(1f)
                    .fillMaxSize()
            ) {

            }
        }
    }
    @Composable
    fun ClickBox(modifier: Modifier = Modifier, colorUpdate: (Color) -> Unit) {
        Box(
            modifier = modifier
                .background(color = Color.Blue)
                .clickable {
                    //点击后产生随机颜色
                    colorUpdate(
                        Color(
                            Random.nextFloat(),
                            Random.nextFloat(),
                            Random.nextFloat(),
                            1f
                        )
                    )
                }
        ) {

        }
    }

    @Composable
    fun 编写SnackBar(){
        val scaffoldState = rememberScaffoldState()
        //文本框的输入文字内容 默认""
        var textFieldState by remember {
            mutableStateOf("")
        }
        val scope = rememberCoroutineScope()
        //熟悉的名字 Flutter 上面的脚手架
        Scaffold(
            modifier = Modifier.fillMaxSize(),
            scaffoldState = scaffoldState
        ) {
            //水平居中
            Column(
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center,
                modifier = Modifier
                    .fillMaxSize()
                    .padding(horizontal = 30.dp)
            )
            {
                TextField(value = textFieldState, label = {
                    Text("Please input your name")
                }, onValueChange = {
                    textFieldState = it
                },
                    singleLine = true,
                    modifier = Modifier.fillMaxWidth()
                )
                Spacer(modifier = Modifier.height(16.dp))
                Box(
                    modifier = Modifier.fillMaxWidth(),
                    contentAlignment = Alignment.CenterEnd
                ) {
                    Button(onClick = {
                        scope.launch {
                            scaffoldState.snackbarHostState.showSnackbar(
                                message = "You put text: $textFieldState"
                            )
                        }
                    }) {
                        Text("Commit")
                    }
                }
            }
        }

    }

    @Composable
    fun 撰写清单(){
        CreateItems()
    }
    @Composable
    private fun CreateItemsOne(){
        val painter1 = painterResource(id = R.drawable.splash_screen)
        val painter2 = painterResource(id = R.drawable.ic_launcher_background)
        LazyColumn(
            verticalArrangement = Arrangement.spacedBy(12.dp),
            contentPadding = PaddingValues(start = 16.dp, end = 16.dp)
        ) {
            itemsIndexed(
                listOf(
                    "Android",
                    "Java",
                    "C",
                    "C++",
                    "Python",
                    "Go",
                    "Php",
                    "Kotlin",
                    "Flutter",
                    "C#",

                    "Android",
                    "Java",
                    "C",
                    "C++",
                    "Python",
                    "Go",
                    "Php",
                    "Kotlin",
                    "Flutter",
                    "C#",

                    "Android",
                    "Java",
                    "C",
                    "C++",
                    "Python",
                    "Go",
                    "Php",
                    "Kotlin",
                    "Flutter",
                    "C#",

                    "Android",
                    "Java",
                    "C",
                    "C++",
                    "Python",
                    "Go",
                    "Php",
                    "Kotlin",
                    "Flutter",
                    "C#",

                    ),

                ) { index: Int, item: String ->
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .background(color = Color.Gray),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Image(
                        modifier = Modifier
                            .padding(top = 16.dp)
                            .height(100.dp)
                            .width(100.dp),
                        painter = if (index % 2 == 0) painter1 else painter2,
                        contentDescription = ""
                    )

                    Text(
                        text = " $item",
                        fontSize = 20.sp,
                        fontWeight = FontWeight.Bold,
                        textAlign = TextAlign.Center,
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(16.dp)
                    )
                }
            }
        }
    }
    @Composable
    private fun CreateItems() {
        val painter1 = painterResource(id = R.drawable.ic_launcher_background)
        val painter2 = painterResource(id = R.drawable.ic_launcher_background)
        LazyColumn() {
            items(200) {
                Column() {
                    Text(
                        text = "Item $it",
                        fontSize = 20.sp,
                        fontWeight = FontWeight.Bold,
                        textAlign = TextAlign.Center,
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(16.dp)
                    )

                    Image(
                        modifier = Modifier
                            .padding(top = 16.dp)
                            .fillMaxWidth(),
                        painter = if (it % 2 == 0) painter1 else painter2,
                        contentDescription = ""
                    )
                }
            }
        }
    }

    @Composable
    fun 编写约束布局(){
        val constraints = ConstraintSet {
            val greenBox = createRefFor("greenBox")
            val redBox = createRefFor("redBox")
            //分界线 50%的位置
            val guideline = createGuidelineFromTop(0.5f)

            //绿色块的约束位置
            constrain(greenBox) {
                top.linkTo(guideline)//顶部连接分界线
                start.linkTo(parent.start)
                width = Dimension.value(100.dp)
                height = Dimension.value(100.dp)
            }

            //红色块的约束位置
            constrain(redBox) {
                top.linkTo(parent.top)
                start.linkTo(greenBox.end)
//                    end.linkTo(parent.end)//红色会在剩余的空间中居中
//                    width = Dimension.fillToConstraints//填充满
                width = Dimension.value(100.dp)
                height = Dimension.value(100.dp)
            }
            createHorizontalChain(greenBox, redBox)//两个均匀分布
        }

        ConstraintLayout(constraints, modifier = Modifier.fillMaxSize()) {
            Box(
                modifier = Modifier
                    .background(color = Color.Green)
                    .layoutId("greenBox")
            )
            Box(
                modifier = Modifier
                    .background(color = Color.Red)
                    .layoutId("redBox")
            )

        }

    }

    @Composable
    fun 撰写按钮(){
        val clickAble = remember {
            mutableStateOf(
                true
            )
        }
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            Button(
                onClick = {
                    clickAble.value = false
                },
                modifier = Modifier
                    .fillMaxWidth(),
                colors = ButtonDefaults.buttonColors(
                    backgroundColor = Color.Green,
                    //不可以点击的颜色
                    disabledBackgroundColor = Color.Gray
                ),
                //不可以点击控制
                enabled = clickAble.value
            ) {
                Text(
                    text = "Click me",
                    modifier = Modifier
                        .fillMaxWidth(),
                    color = Color.White,
                    textAlign = TextAlign.Center,
                    fontSize = 20.sp,
                )
            }
        }
    }

    @Composable
    fun CheckBox(){
        /*使用CheckBox没法加Icon,使用IconButton*/
        CheckBoxWithIcon(){}
    }
    @Composable
    fun CheckBoxWithIcon(onClick: (click:Boolean) -> Unit){
        val icon = remember { mutableStateOf(R.mipmap.xaingyu) }
        var clicked = false
        IconButton(modifier = Modifier
            .padding(2.dp), onClick = {
            clicked = !clicked
            icon.value =
                if (clicked) R.mipmap.xaingyu else R.mipmap.xaingyu
            onClick.invoke(clicked)
        }) {
            Image(
                painter = painterResource(id = icon.value),
                contentDescription = null
            )
        }
    }

    @Composable
    fun 原生xml加入Compose(){
        /*R.layout.xml_compose*/
        /*val mLlContainer = context.findViewById<ComposeView>(R.id.mComposeView)
        mLlContainer.setContent {
            ComposeContent()
        }*/
    }

    @Composable
    fun compose加入xml(){

    }
    //@SuppressLint("SetTextI18n")  ??静态检查器.忽略指定警告
    @Composable
    fun ComposeContent() {
        LazyColumn(modifier = Modifier.fillMaxWidth(), content = {
            item {
                Text(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(100.dp)
                        .background(color = Color.Green),
                    textAlign = TextAlign.Center,
                    text = "Compose header",
                )
            }
            items(count = 6) {
                AndroidView(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(8.dp),
                    factory = { ctx ->
                        val view =
                            LayoutInflater.from(ctx).inflate(R.layout.xml_compose, null)
                        //view.findViewById<TextView>(R.id.tvText).text = "Xml Item $it"
                        view
                    },
                )
            }
            item {
                Text(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(100.dp)
                        .padding(8.dp)
                        .background(color = Color.Yellow),
                    textAlign = TextAlign.Center,
                    text = "Compose Footer",
                )
            }
        })
    }

    @Composable
    fun 简易朋友圈列表(){
        FriendsCircle()
    }
    @Preview
    @Composable
    fun FriendsCircle() {
        val screenWidth = getScreenWidth()

        var picWidth by remember { mutableStateOf(0) }

        LazyColumn(modifier = Modifier.fillMaxSize(), content = {
            items(count = 10) {
                ConstraintLayout(modifier = Modifier.fillMaxWidth()) {
                    val (headRef, titleRef, desRef, picsRef) = createRefs()
                    Image(
                        modifier = Modifier
                            .size(40.dp)
                            .padding(4.dp)
                            .clip(CircleShape)
                            .border(1.dp, Color.DarkGray, CircleShape)
                            .constrainAs(headRef) {
                                top.linkTo(parent.top, margin = 10.dp)
                                start.linkTo(parent.start, margin = 10.dp)
                            },
                        painter = painterResource(id = R.drawable.ic_launcher_background),
                        contentDescription = null
                    )
                    Text(
                        modifier = Modifier
                            .constrainAs(titleRef) {
                                top.linkTo(headRef.top)
                                start.linkTo(headRef.end, margin = 10.dp)
                                end.linkTo(parent.end, margin = 10.dp)
                                bottom.linkTo(headRef.bottom)
                                width = Dimension.fillToConstraints
                            },

                        text = "这是一个标题 $it",
                        textAlign = TextAlign.Start,
                        fontSize = 20.sp,
                        color = Color.Black,
                        fontWeight = FontWeight.Bold,
                    )

                    Text(
                        modifier = Modifier.constrainAs(desRef) {
                            top.linkTo(headRef.bottom, margin = 10.dp)
                            start.linkTo(headRef.end, margin = 10.dp)
                            end.linkTo(parent.end, margin = 10.dp)
                            width = Dimension.fillToConstraints
                        },
                        text = "王嘉尔，1994年3月28日出生于香港，中国香港流行乐男歌手、音乐人、主持人、设计师、创意总监 。王嘉尔，1994年3月28日出生于香港，中国香港流行乐男歌手、音乐人、主持人、设计师、创意总监 王嘉尔，1994年3月28日出生于香港，中国香港流行乐男歌手、音乐人、主持人、设计师、创意总监 王嘉尔，1994年3月28日出生于香港，中国香港流行乐男歌手、音乐人、主持人、设计师、创意总监  $it"
                    )


                    Column(modifier = Modifier
                        .fillMaxWidth()
                        .onSizeChanged {
                            picWidth = it.width
                        }
                        .constrainAs(picsRef) {
                            top.linkTo(desRef.bottom, margin = 10.dp)
                            start.linkTo(headRef.end, margin = 10.dp)
                            end.linkTo(parent.end, margin = 10.dp)
                            width = Dimension.fillToConstraints
                        }
                    ){
                        Row(modifier = Modifier
                            .fillMaxWidth()) {
                            for (index in 0..2){
                                PicItem(pxToDp((picWidth/3)).dp)
                            }
                        }
                        Spacer(modifier = Modifier.fillMaxWidth().height(4.dp))
                        Row(modifier = Modifier
                            .fillMaxWidth()) {
                            for (index in 0..2){
                                PicItem(pxToDp((picWidth/3)).dp)
                            }
                        }
                        Spacer(modifier = Modifier.fillMaxWidth().height(4.dp))
                        Row(modifier = Modifier
                            .fillMaxWidth()) {
                            for (index in 0..2){
                                PicItem(pxToDp((picWidth/3)).dp)
                            }
                        }
                    }


                    //稍微 有些卡 列表嵌套列表的形式
//                    val numbers = (0..8).toList()
//                    val pxValue = with(LocalDensity.current) { 10.dp.toPx() }
//                    val picWidth = (screenWidth - pxValue * 2) / 3
//
//                    LazyVerticalGrid(
//                        cells = GridCells.Fixed(3),
//                        modifier = Modifier
//                            .fillMaxWidth()
//                            .height(pxToDp(picWidth.toInt() * 3).dp)
//                            .constrainAs(picsRef) {
//                                top.linkTo(desRef.bottom, margin = 10.dp)
//                                start.linkTo(headRef.end, margin = 10.dp)
//                                end.linkTo(parent.end, margin = 10.dp)
//                                width = Dimension.fillToConstraints
//                            }
//
//                    ) {
//                        items(numbers.size) {
//                            Image(
//                                modifier = Modifier
//                                    .height(pxToDp(picWidth.toInt()).dp)
//                                    .padding(horizontal = 2.dp)
//                                    .clip(RoundedCornerShape(corner = CornerSize(4.dp)))
//                                    .border(
//                                        1.dp,
//                                        Color.Gray,
//                                        RoundedCornerShape(corner = CornerSize(4.dp))
//                                    )
//                                    .aspectRatio(1f),
//                                painter = painterResource(id = R.drawable.vector_empty),
//                                contentDescription = null
//                            )
//                        }
//                    }
                }
            }
        })
    }

    @Composable
    fun PicItem(width: Dp){
        Image(
            modifier = Modifier
                .width(width)
                .padding(horizontal = 2.dp)
                .clip(RoundedCornerShape(corner = CornerSize(4.dp)))
                .border(
                    1.dp,
                    Color.Gray,
                    RoundedCornerShape(corner = CornerSize(4.dp))
                )
                .aspectRatio(1f),
            painter = painterResource(id = R.drawable.ic_launcher_background),
            contentDescription = null
        )
    }


    private fun pxToDp(px: Int): Int {
        return (px / Resources.getSystem().displayMetrics.density).toInt()
    }

    private fun getScreenWidth(): Int {
        return Resources.getSystem().displayMetrics?.widthPixels ?: 0
    }

    @Composable
    fun composeCameraX(){
        SimpleCameraPreview()
    }
    @Composable
    fun SimpleCameraPreview() {
        /*val lifecycleOwner = LocalLifecycleOwner.current
        val context = LocalContext.current
        val cameraProviderFuture = remember { ProcessCameraProvider.getInstance(context) }
        AndroidView(
            factory = { ctx ->
                val preview = PreviewView(context).apply {
                    this.scaleType = scaleType
                    layoutParams = ViewGroup.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.MATCH_PARENT
                    )
                    // Preview is incorrectly scaled in Compose on some devices without this
                    implementationMode = PreviewView.ImplementationMode.COMPATIBLE
                }

                val executor = ContextCompat.getMainExecutor(ctx)
                cameraProviderFuture.addListener({
                    val cameraProvider = cameraProviderFuture.get()
                    bindPreview(
                        lifecycleOwner,
                        preview,
                        cameraProvider,
                    )
                }, executor)
                preview
            },
            modifier = Modifier.fillMaxSize(),
        )*/
    }

    private fun bindPreview(
        lifecycleOwner: LifecycleOwner,
        /*previewView: PreviewView,
        cameraProvider: ProcessCameraProvider*/
    ) {
       /* val preview = androidx.camera.core.Preview.Builder().build()
        val cameraSelector: CameraSelector = CameraSelector.Builder()
            .requireLensFacing(CameraSelector.LENS_FACING_BACK)
            .build()
        preview.setSurfaceProvider(previewView.surfaceProvider)
        val camera = cameraProvider.bindToLifecycle(lifecycleOwner, cameraSelector, preview)
//        camera.cameraControl.enableTorch(true)
        camera.cameraControl.cancelFocusAndMetering()*/
//        camera.cameraControl.setZoomRatio(0.5f)
//        camera.cameraInfo.

    }

    @Composable
    fun Compose权限申请Permission(){
        FeatureThatRequiresCameraPermission { startAppSettings() }
    }
    private fun startAppSettings() {
        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        /*intent.data = Uri.parse("package:$packageName")
        startActivity(intent)*/
    }


    @Composable
    private fun FeatureThatRequiresCameraPermission(navigateToSettingsScreen: () -> Unit) {
        // Track if the user doesn't want to see the rationale any more.
        var doNotShowRationale by rememberSaveable { mutableStateOf(false) }

        /*val cameraPermissionState = rememberPermissionState(android.Manifest.permission.CAMERA)
        PermissionRequired(
            permissionState = cameraPermissionState,
            permissionNotGrantedContent = {
                if (doNotShowRationale) {
                    Text("Feature not available")
                } else {
                    Column {
                        Text("The camera is important for this app. Please grant the permission.")
                        Spacer(modifier = Modifier.height(8.dp))
                        Row {
                            Button(onClick = { cameraPermissionState.launchPermissionRequest() }) {
                                Text("Ok!")
                            }
                            Spacer(Modifier.width(8.dp))
                            Button(onClick = { doNotShowRationale = true }) {
                                Text("Nope")
                            }
                        }
                    }
                }
            },
            permissionNotAvailableContent = {
                Column {
                    Text(
                        "Camera permission denied. See this FAQ with information about why we " +
                                "need this permission. Please, grant us access on the Settings screen."
                    )
                    Spacer(modifier = Modifier.height(8.dp))
                    Button(onClick = navigateToSettingsScreen) {
                        Text("Open Settings")
                    }
                }
            }
        ) {
            Text("Camera permission Granted")
        }*/
    }

    @Composable
    private fun FeatureThatRequiresCameraPermission1(
        navigateToSettingsScreen: () -> Unit
    ) {
        // Track if the user doesn't want to see the rationale any more.
        var doNotShowRationale by rememberSaveable { mutableStateOf(false) }

        // Camera permission state
        /*val cameraPermissionState = rememberPermissionState(
            android.Manifest.permission.CAMERA
        )

        when {
            // If the camera permission is granted, then show screen with the feature enabled
            cameraPermissionState.hasPermission -> {
                Text("Camera permission Granted")
            }
            // If the user denied the permission but a rationale should be shown, or the user sees
            // the permission for the first time, explain why the feature is needed by the app and allow
            // the user to be presented with the permission again or to not see the rationale any more.
            cameraPermissionState.shouldShowRationale ||
                    !cameraPermissionState.permissionRequested -> {
                if (doNotShowRationale) {
                    Text("Feature not available")
                } else {
                    Column {
                        Text("The camera is important for this app. Please grant the permission.")
                        Spacer(modifier = Modifier.height(8.dp))
                        Row {
                            Button(onClick = { cameraPermissionState.launchPermissionRequest() }) {
                                Text("Request permission")
                            }
                            Spacer(Modifier.width(8.dp))
                            Button(onClick = { doNotShowRationale = true }) {
                                Text("Don't show rationale again")
                            }
                        }
                    }
                }
            }
            // If the criteria above hasn't been met, the user denied the permission. Let's present
            // the user with a FAQ in case they want to know more and send them to the Settings screen
            // to enable it the future there if they want to.
            else -> {
                Column {
                    Text(
                        "Camera permission denied. See this FAQ with information about why we " +
                                "need this permission. Please, grant us access on the Settings screen."
                    )
                    Spacer(modifier = Modifier.height(8.dp))
                    Button(onClick = navigateToSettingsScreen) {
                        Text("Open Settings")
                    }
                }
            }
        }*/
    }

    @Composable
    fun Clock1() {
        val hour = remember {
            mutableStateOf(0f)
        }
        val minute = remember {
            mutableStateOf(0f)
        }
        val second = remember {
            mutableStateOf(0f)
        }

        LaunchedEffect(key1 = "") {
            while (true) {
                val cal = Calendar.getInstance()
                hour.value = cal.get(Calendar.HOUR).toFloat()
                minute.value = cal.get(Calendar.MINUTE).toFloat()
                second.value = cal.get(Calendar.SECOND).toFloat()
                delay(1000)
            }
        }
        val diameter = 200.dp
        val color1 = Color.Black
        Canvas(
            modifier = Modifier.size(diameter, diameter)
        ) {

            val outCircleR = size.width / 2
            val innerCircleR = (size.width / 2 * 0.8).toFloat()
            drawCircle(
                brush = Brush.radialGradient(
                    colors = listOf(Color.DarkGray, Color.Gray)
                )
                ,
                radius = outCircleR,
                alpha = 0.5f
            )
            //最里面的圆心
            drawCircle(color = color1, radius = size.width * 0.02f)
            //外部大圆
            drawCircle(color = color1, radius = outCircleR, style = Stroke(4f))

            translate(size.width / 2, size.height / 2) {
                //画刻度
                drawIntoCanvas { canvas ->
                    //将 Jetpack Compose 环境的 Paint 对象转换为原生的 Paint 对象
                    val textPaint = Paint().asFrameworkPaint().apply {
                        isAntiAlias = true
//                            isDither = true
                        typeface = Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD)
                        textAlign = android.graphics.Paint.Align.CENTER
                    }
                    textPaint.color = android.graphics.Color.BLACK
                    textPaint.textSize = 50f
                    //拿到原生的 Canvas 对象
                    val nativeCanvas = canvas.nativeCanvas
                    var text = 3
                    for (index in 0..330 step 30) {

                        val centerX = (innerCircleR * cos(index * Math.PI / 180)).toFloat()
                        val centerY = (innerCircleR * sin(index * Math.PI / 180)).toFloat()
                        nativeCanvas.drawText(
                            text.toString(),
                            centerX, centerY + 25f, textPaint
                        )

                        text++
                        if (text > 12) {
                            text = 1
                        }
                    }
                }
                //画时针
                //hour的角度 -3 + 分钟  / 12   * 360
                val hourLength = innerCircleR * 0.6f
                val hourAngle = (hour.value.plus(minute.value.div(60)).minus(3)).div(12) * 360
                drawLine(
                    color = color1,
                    start = Offset.Zero,
                    end = Offset(
                        (hourLength * cos(hourAngle * Math.PI / 180)).toFloat(),
                        (hourLength * sin(hourAngle * Math.PI / 180)).toFloat()
                    ),
                    strokeWidth = 8f,
                    cap = StrokeCap.Round
                )
                //画分针
                val minuteLength = innerCircleR * 0.9f
                val minuteAngle =
                    (minute.value.plus(second.value.div(60)).minus(15)).div(60) * 360
                drawLine(
                    color = color1,
                    start = Offset.Zero,
                    end = Offset(
                        (minuteLength * cos(minuteAngle * Math.PI / 180)).toFloat(),
                        (minuteLength * sin(minuteAngle * Math.PI / 180)).toFloat()
                    ),
                    strokeWidth = 6f,
                    cap = StrokeCap.Round
                )
                //画秒针
                val secondLength = outCircleR * 0.9f
                val secondAngle = second.value.div(60) * 360
                drawLine(
                    color = color1,
                    start = Offset.Zero,
                    end = Offset(
                        (secondLength * cos(secondAngle * Math.PI / 180)).toFloat(),
                        (secondLength * sin(secondAngle * Math.PI / 180)).toFloat()
                    ),
                    strokeWidth = 2f,
                    cap = StrokeCap.Round
                )
            }
        }
    }

    @Composable
    fun Clock() {
        val hour = remember {
            mutableStateOf(0f)
        }
        val minute = remember {
            mutableStateOf(0f)
        }
        val second = remember {
            mutableStateOf(0f)
        }

        LaunchedEffect(key1 = "") {
            while (true) {
                val cal = Calendar.getInstance()
                hour.value = cal.get(Calendar.HOUR).toFloat()
                minute.value = cal.get(Calendar.MINUTE).toFloat()
                second.value = cal.get(Calendar.SECOND).toFloat()
                delay(1000)
            }
        }

        val diameter = 200.dp
        val color1 = Color.Black

        Canvas(
            modifier = Modifier
                .size(diameter, diameter)
        ) {

            val outCircleR = size.width / 2
            val innerCircleR = (size.width / 2 * 0.8).toFloat()
            //最里面的圆心
            drawCircle(color = color1, radius = size.width * 0.02f)
            //外部大圆
            drawCircle(color = color1, radius = outCircleR, style = Stroke(4f))
            //里面小圆
            drawCircle(
                color = color1,
                radius = innerCircleR,
                style = Stroke(2f)
            )
            translate(size.width / 2, size.height / 2) {
                //画刻度
                for (index in 0..330 step 30) {
                    drawLine(
                        color = color1,
                        start = Offset(
                            (innerCircleR * 1.05f * cos(index * Math.PI / 180)).toFloat(),
                            (innerCircleR * 1.05f * sin(index * Math.PI / 180)).toFloat()
                        ),
                        end = Offset(
                            (outCircleR * 0.95f * cos(index * Math.PI / 180)).toFloat(),
                            (outCircleR * 0.95f * sin(index * Math.PI / 180)).toFloat()
                        ),
                        strokeWidth = 8f,
                        cap = StrokeCap.Round
                    )
                }

                //画时针
                //hour的角度 -3 + 分钟  / 12   * 360
                val hourLength = innerCircleR * 0.6f
                val hourAngle = (hour.value.plus(minute.value.div(60)).minus(3)).div(12) * 360
                drawLine(
                    color = color1,
                    start = Offset.Zero,
                    end = Offset(
                        (hourLength * cos(hourAngle * Math.PI / 180)).toFloat(),
                        (hourLength * sin(hourAngle * Math.PI / 180)).toFloat()
                    ),
                    strokeWidth = 8f,
                    cap = StrokeCap.Round
                )
                //画分针
                val minuteLength = innerCircleR * 0.9f
                val minuteAngle =
                    (minute.value.plus(second.value.div(60)).minus(15)).div(60) * 360
                drawLine(
                    color = color1,
                    start = Offset.Zero,
                    end = Offset(
                        (minuteLength * cos(minuteAngle * Math.PI / 180)).toFloat(),
                        (minuteLength * sin(minuteAngle * Math.PI / 180)).toFloat()
                    ),
                    strokeWidth = 6f,
                    cap = StrokeCap.Round
                )
                //画秒针
                val secondLength = outCircleR * 0.9f
                val secondAngle = second.value.div(60) * 360
                drawLine(
                    color = color1,
                    start = Offset.Zero,
                    end = Offset(
                        (secondLength * cos(secondAngle * Math.PI / 180)).toFloat(),
                        (secondLength * sin(secondAngle * Math.PI / 180)).toFloat()
                    ),
                    strokeWidth = 2f,
                    cap = StrokeCap.Round
                )
            }
        }
    }

    data class Item(
        var item: String,
        var isNew: Boolean,
    )
    @Composable
    fun ComposeItem(){
        Item()
    }
    @SuppressLint("UnrememberedMutableState")
    @Composable
    fun Item() {

        val context = LocalContext.current
        val list = mutableStateListOf<Item>()

        repeat(20) {
            list.add(Item(item = "Item $it", isNew = false))
        }

        Column(modifier = Modifier
            .fillMaxSize()
            .padding(start = 10.dp, end = 10.dp)) {
            Button(modifier = Modifier
                .fillMaxWidth()
                .padding(top = 10.dp), onClick = {

                val index = (0..5).random()
                if (index < list.size) {
                    list.add(index, Item(item = "insert Item ${(0..5).random()}", isNew = true))
                } else {
                    list.add(0, Item(item = "insert Item ${(0..5).random()}", isNew = true))
                }

            }) {
                Text(text = "add Item")
            }

            Button(modifier = Modifier
                .fillMaxWidth()
                .padding(top = 10.dp), onClick = {
                val index = (0..5).random()
                if (index < list.size) {
                    list.removeAt(index)
                } else {
                    Toast.makeText(context, "无此条目", Toast.LENGTH_SHORT).show()
                }
            }) {
                Text(text = "remove Item")
            }

            LazyColumn(content = {
                items(count = list.size, itemContent = { index ->
                    Box(modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = 10.dp, bottom = 10.dp)
                        .background(color = if (list[index].isNew) Color.LightGray else Color.DarkGray)) {
                        Text(modifier = Modifier
                            .fillMaxWidth()
                            .padding(top = 10.dp, bottom = 10.dp), fontWeight = FontWeight.Medium, fontSize = 20.sp, color = Color.White, textAlign = TextAlign.Center, text = list[index].item)
                    }
                })
            })
        }
    }

    @Composable
    fun 难用控件DialogTextField(){
        /*textfield自定义难,调整使用BasicTextField*/
        //CustomTextField()
        /*dialogbug:点击dialog按钮以外的地方,可能导致dialog卡死_ws未发现,
        使用alert dialog,text可以自定义内容的,可是自定义内容的高度有限制,导致对话框的内容不能正常填充,
        歪招,text写为null,在button里填充内容
        */
        //ShowCustomDialog()
    }

    @Composable
    fun CustomTextField(
        text: MutableState<String>,
        modifier: Modifier = Modifier,
        hint: String? = null,
        onTextChange: String.() -> Unit = {},
        leadingIcon: @Composable (() -> Unit)? = null,
        trailingIcon: @Composable (() -> Unit)? = null,
        keyboardOptions: KeyboardOptions = KeyboardOptions.Default,
        keyboardActions: String.() -> Unit = {},
        textFieldStyle: TextStyle = LocalTextStyle.current,
        hintTextStyle: TextStyle = LocalTextStyle.current,
    ) {
        Row(
            modifier = modifier,
            verticalAlignment = Alignment.CenterVertically,
        ) {
            leadingIcon?.invoke()
            BasicTextField(
                value = text.value,
                onValueChange = { str ->
                    text.value = str
                    onTextChange.invoke(str)
                },
                cursorBrush = SolidColor(Teal200),
                singleLine = true,
                modifier = Modifier
                    .weight(1f)
                    .padding(start = 15.dp),
                textStyle = textFieldStyle,
                decorationBox = { innerTextField ->
                    if (text.value.isBlank() && !hint.isNullOrBlank())
                        Box(
                            modifier = Modifier.fillMaxHeight(),
                            contentAlignment = Alignment.CenterStart
                        ) {
                            innerTextField()
                            Text(
                                hint ?: "",
                                modifier = Modifier.fillMaxWidth(),
                                style = hintTextStyle,
                            )
                        } else innerTextField()

                },
                keyboardActions = KeyboardActions {
                    keyboardActions(text.value)
                },
                keyboardOptions = keyboardOptions
            )
            trailingIcon?.invoke()
        }
    }


    @Composable
    fun ShowCustomDialog(
        showDialog: MutableState<Boolean>,
        modifier: Modifier = Modifier,
        content: @Composable () -> Unit,
        cancelText: String,
        okText: String,
        cancelOnClick: () -> Unit,
        okOnClick: () -> Unit,
        dismissOnClickOutside: Boolean = true,
        dismissOnBackPress: Boolean = true,
    ) {
        if (showDialog.value) {
            AlertDialog(
                modifier = modifier
                    .fillMaxWidth()
                    .background(color = Color.Blue, shape = RoundedCornerShape(9.dp)),
                shape = RoundedCornerShape(9.dp),
                properties = DialogProperties(
                    dismissOnClickOutside = dismissOnClickOutside,
                    dismissOnBackPress = dismissOnBackPress
                ),
                onDismissRequest = {
                    showDialog.value = false
                },
                title = null,
                text = null,
                buttons = {
                    Column(modifier = Modifier
                        .fillMaxWidth()
                        .wrapContentHeight()) {
                        content()
                        //HorizontalDivider(color = Color.Green, height = 1.dp)
                        Row(modifier = Modifier.fillMaxWidth().height(50.dp)) {
                            TextButton(
                                modifier = Modifier
                                    .weight(1f),
                                onClick = {
                                    cancelOnClick.invoke()
                                    showDialog.value = false
                                },
                            ) {
                                Text(text = cancelText, color = Color.Green, fontSize = 16.sp)
                            }
                            Divider(
                                modifier = Modifier
                                    .width(1.dp)
                                    .fillMaxHeight(),
                                color = Color.Green
                            )
                            TextButton(
                                modifier = Modifier
                                    .weight(1f),
                                onClick = {
                                    okOnClick.invoke()
                                    showDialog.value = false
                                },
                            ) {
                                Text(okText, color = Color.Green, fontSize = 16.sp)
                            }
                        }
                    }
                }
            )
        }
    }


    @Composable
    fun TextField光标位置和键盘事件(){
        //项目地址https://github.com/Qdafengzi/ComposeDemo
        //KeyboardPage()
    }

    @RequiresApi(Build.VERSION_CODES.R)
    @ExperimentalComposeUiApi
    @Composable
    fun KeyboardPage(navCtrl: NavHostController, title: String) {
        val context = LocalContext.current
        WindowCompat.setDecorFitsSystemWindows((context as Activity).window, false)

        var keyboardStatus by remember {
            mutableStateOf(false)
        }

        (context as Activity).window.decorView.addKeyboardInsetListener {
            keyboardStatus = it
        }

        val focusRequester = FocusRequester()
        /*CommonToolbar(navCtrl, title) {
            ProvideWindowInsets {
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally,
                    modifier = Modifier
                        .fillMaxWidth()
                        .statusBarsPadding()
                        .navigationBarsWithImePadding()
                ) {
                    val text = remember {
                        mutableStateOf(TextFieldValue())
                    }

                    TextField(
                        modifier = Modifier
                            .fillMaxWidth()
                            .focusRequester(focusRequester),
                        value = text.value,
                        onValueChange = { text.value = it },
                        placeholder = {
                            Text(text = "请输入内容", color = Color.LightGray)
                        }

                    )
                    Spacer(Modifier.weight(1f))
                    if (keyboardStatus) {
                        Box(modifier = Modifier.fillMaxWidth()) {
                            Row(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .background(color = Color.DarkGray)
                                    .padding(top = 10.dp, bottom = 10.dp),
                                horizontalArrangement = Arrangement.SpaceEvenly,
                                verticalAlignment = Alignment.CenterVertically,
                            ) {
                                Text(
                                    text = "😀",
                                    modifier = Modifier
                                        .weight(1f)
                                        .clickable {
                                            text.value =
                                                text.value.copy(
                                                    text = text.value.text + "😀",
                                                    selection = TextRange((text.value.text + "😀").length)
                                                )
                                        },
                                    textAlign = TextAlign.Center,
                                )
                                Text(
                                    text = "🤣",
                                    modifier = Modifier
                                        .weight(1f)
                                        .clickable {
                                            text.value =
                                                text.value.copy(
                                                    text = text.value.text + "🤣",
                                                    selection = TextRange((text.value.text + "🤣").length)
                                                )
                                        },
                                    textAlign = TextAlign.Center,
                                )
                                Text(
                                    text = "😇",
                                    modifier = Modifier
                                        .weight(1f)
                                        .clickable {
                                            text.value =
                                                text.value.copy(
                                                    text = text.value.text + "😇",
                                                    selection = TextRange((text.value.text + "😇").length)
                                                )
                                        },
                                    textAlign = TextAlign.Center,
                                )
                                Text(
                                    text = "🐺",
                                    modifier = Modifier
                                        .weight(1f)
                                        .clickable {
                                            text.value =
                                                text.value.copy(
                                                    text = text.value.text + "🐺",
                                                    selection = TextRange((text.value.text + "🐺").length)
                                                )
                                        },
                                    textAlign = TextAlign.Center,
                                )
                                Text(
                                    text = "🐽",
                                    modifier = Modifier
                                        .weight(1f)
                                        .clickable {
                                            text.value =
                                                text.value.copy(
                                                    text = text.value.text + "🐽",
                                                    selection = TextRange((text.value.text + "🐽").length)
                                                )
                                        },
                                    textAlign = TextAlign.Center,
                                )
                                Text(
                                    text = "🐸",
                                    modifier = Modifier
                                        .weight(1f)
                                        .clickable {
                                            text.value = text.value.copy(
                                                text = text.value.text + "🐸",
                                                selection = TextRange((text.value.text + "🐸").length),
                                            )
                                        },
                                    textAlign = TextAlign.Center,
                                )
                            }
                        }
                    }
                }
            }
        }*/
    }

    @RequiresApi(Build.VERSION_CODES.R)
    fun View.addKeyboardInsetListener(keyboardCallback: (visible: Boolean) -> Unit) {
        doOnLayout {
            //get init state of keyboard
            var keyboardVisible = rootWindowInsets?.isVisible(WindowInsets.Type.ime()) == true

            //callback as soon as the layout is set with whether the keyboard is open or not
            keyboardCallback(keyboardVisible)

            //whenever there is an inset change on the App, check if the keyboard is visible.
            setOnApplyWindowInsetsListener { _, windowInsets ->
                val keyboardUpdateCheck =
                    rootWindowInsets?.isVisible(WindowInsets.Type.ime()) == true
                //since the observer is hit quite often, only callback when there is a change.
                if (keyboardUpdateCheck != keyboardVisible) {
                    keyboardCallback(keyboardUpdateCheck)
                    keyboardVisible = keyboardUpdateCheck
                }

                windowInsets
            }
        }
    }

    @Composable
    fun nestedScroll向下滑动隐藏标题(){
        val toolbarHeight = 48.dp
        val toolbarHeightPx = with(LocalDensity.current) { toolbarHeight.roundToPx().toFloat() }
        val toolbarOffsetHeightPx = remember { mutableStateOf(0f) }
        val nestedScrollConnection = remember {
            object : NestedScrollConnection {
                override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
                    //y方向的偏移量
                    val delta = available.y
                    val newOffset = toolbarOffsetHeightPx.value + delta
                    toolbarOffsetHeightPx.value = newOffset.coerceIn(-toolbarHeightPx, 0f)
                    return Offset.Zero
                }
            }
        }
        Box(
            Modifier
                .fillMaxSize()
                .nestedScroll(nestedScrollConnection)
        ) {
            LazyColumn(contentPadding = PaddingValues(top = toolbarHeight)) {
                items(100) { index ->
                    Text(
                        stringResource(id = R.string.app_name, index),
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(16.dp)
                    )
                }
            }
            TopAppBar(
                modifier = Modifier
                    .height(toolbarHeight)
                    .offset { IntOffset(x = 0, y = toolbarOffsetHeightPx.value.roundToInt()) },
                title = {
                    Text(
                        stringResource(id = R.string.app_name, toolbarOffsetHeightPx.value)
                    )
                }
            )
        }

    }

    @Composable
    fun 仿京东商品详情页面3d全景图(){
        //使用OpenGL通过GLSL来实现
        //通过多张图片实现
        //https://github.com/Qdafengzi/ComposeDemo
    }

    fun 鸿蒙点击bug(){
        //点击事件没用,机型,鸿蒙大部分机型(ws还没发现)
        /*
        界面为全屏的拍摄界面,使用了SystemUIController导致问题发生
        解决去掉一下代码
         val systemUiController: SystemUiController = rememberSystemUiController()
 systemUiController.isSystemBarsVisible = false // Status & Navigation bars
        */
    }

    @Composable
    fun compose快速点击防抖(){
        //DebouncedClickable()
    }
    @Composable
    fun DebouncedClickable(navCtrl: NavHostController, title: String) {

        val clicked = remember {
            mutableStateOf(false)
        }

        /*CommonToolbar(navCtrl, title) {
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .background(color = if (clicked.value) Color.Blue else Color.Red),
            ) {
                Box(modifier = Modifier.fillMaxSize().debouncedClickable(
                    enabled = true,
                    onClick = {
                        clicked.value = !clicked.value
                    },
//               delay = 10L,
                    delay = 1000L,
                )) {
                    Text(
                        text = if (clicked.value) "蓝色" else "红色",
                        color = Color.White,
                        fontSize = 30.sp,
                        fontWeight = FontWeight.SemiBold
                    )
                }
            }
        }*/
    }

    //Modifier 的扩展方法处理如下
    fun Modifier.debouncedClickable(enabled: Boolean, onClick: () -> Unit, delay: Long = 300) =
        composed {
            var clicked by remember {
                mutableStateOf(!enabled)
            }
            LaunchedEffect(key1 = clicked, block = {
                if (clicked) {
                    delay(delay)
                    clicked = !clicked
                }
            })

            Modifier.clickable(if (enabled) !clicked else false) {
                clicked = !clicked
                onClick()
            }
        }

}